﻿using System;
using System.Collections.Generic;
using System.Json;
using System.Net;

namespace SilverPortal
{
	public interface IStateStorageProvider
	{
		Dictionary<string, string> Load();
		void Save(Dictionary<string, string> state);
	}

	/// <summary>
	/// State storage provider that uses a cookie on the local browser.
	/// </summary>
	public class CookieStateProvider : IStateStorageProvider
	{
		private const string CookieName = "portalstate";

		public Dictionary<string, string> Load()
		{
			var state = new Dictionary<string, string>();
			string cookie = CookieUtil.Get(CookieName);
			if (String.IsNullOrEmpty(cookie))
				return state;

			var json = (JsonObject)JsonObject.Parse(cookie);
			foreach (string key in json.Keys)
			{
				JsonValue value = json[key];
				if (value.JsonType == JsonType.String)
					state[key] = (string)json[key];
				else if (value.JsonType == JsonType.Number)
					state[key] = ((double)value).ToString();
				else
					continue;
			}
			return state;
		}

		public void Save(Dictionary<string, string> state)
		{
			var list = new List<KeyValuePair<string, JsonValue>>();
			foreach (string key in state.Keys)
			{
				list.Add(new KeyValuePair<string, JsonValue>(key, state[key]));
			}
			var json = new JsonObject(list);
			CookieUtil.Set(CookieName, json.ToString());
		}
	}


	public class PortalState
	{
		private IStateStorageProvider _storageProvider;
		private Dictionary<string, string> _state;

		public PortalState(IStateStorageProvider storageProvider)
		{
			_storageProvider = storageProvider;
			_state = storageProvider.Load();
		}

		/// <summary>
		/// Get a user state value.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string this[string key]
		{
			get
			{
				string value;
				if (_state.TryGetValue(key, out value))
					return value;
				return null;
			}
			set
			{
				_state[key] = value;
				_storageProvider.Save(_state);
			}
		}
	}
}